package com.action;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.opensymphony.xwork2.ActionContext;

import com.entity.Cart;
import com.entity.Order;
import com.entity.OrderItem;
import com.entity.Product;
import com.entity.User;
import com.service.OrderService;
import com.service.Impl.OrderServiceImpl;
import com.util.JedisUtil;
import org.apache.commons.lang3.SerializationUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import redis.clients.jedis.Jedis;

import static com.util.OrderNoUtil.getOrderNo;
@Controller
@Scope("prototype")
public class OrderAction {
	@Autowired
	private OrderService service;
	private Integer addressId;
	private List<OrderItem> oiList=new ArrayList<>();
	private Double totalPrice;
	private String No;
	private List<Order> orders;

	public List<Order> getOrders() {
		return orders;
	}

	public void setOrders(List<Order> orders) {
		this.orders = orders;
	}

	public String getNo() {
		return No;
	}
	public void setNo(String no) {
		No = no;
	}
	public Double getTotalPrice() {
		return totalPrice;
	}
	public void setTotalPrice(Double totalPrice) {
		this.totalPrice = totalPrice;
	}
	public List<OrderItem> getOiList() {
		return oiList;
	}
	public void setOiList(List<OrderItem> oiList) {
		this.oiList = oiList;
	}
	public Integer getAddressId() {
		return addressId;
	}
	public void setAddressId(Integer addressId) {
		this.addressId = addressId;
	}
	public String insertOrder(){
		Map<String, Object> session = ActionContext.getContext().getSession();
		User user=(User)session.get("u");
		Jedis jedis = JedisUtil.getJedis();
		byte[] key = SerializationUtils.serialize(user.getUserId());
		byte[] cartByte = jedis.get(key);
		Cart cart = (Cart) SerializationUtils.deserialize(cartByte);
		User u=(User)session.get("u");
		Order order=new Order();
		String orderNo=getOrderNo();
		order.setOrderId(orderNo);
		order.setTotalPrice(cart.getTotalPrice());
		order.setUserId(u.getUserId());
		order.setAddressId(addressId);
		Map<Integer, Product> map = cart.getAddMap();
		Set<Integer> set = map.keySet();
		for(Integer i:set){
			OrderItem item=new OrderItem();
			item.setBookId(i);
			item.setDangPrice(map.get(i).getBook().getBookPrice());
			item.setCount(map.get(i).getCount());
			item.setOrderId(order.getOrderId());
			oiList.add(item);
		}
		service.insertOrder(order, oiList);
		totalPrice=cart.getTotalPrice();
		No=orderNo;
		return "insertOrder";
	}
	public String selectOrderById(){
		Map<String, Object> session = ActionContext.getContext().getSession();
		User user=(User)session.get("u");
		Integer userId=user.getUserId();
		orders=service.selectOrderById(userId);
		return "selectOrderById";
	}
}
